package com.zyt.demo.cookie;

import org.jetbrains.annotations.NotNull;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@WebServlet("/CookieLoginServlet")
public class CookieLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String lastFromCookie = this.getCookieValue(request,"last_time");
        if (lastFromCookie != null) {
            System.out.println("lastFromCookie = " + lastFromCookie);
        }

        // 写入Cookie
        Date date = new Date();
        Cookie cookie = new Cookie("last_time", date.toString());
        response.addCookie(cookie);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    private String getCookieValue(@NotNull HttpServletRequest request, String cookiename) {
        if (request.getCookies() == null) {
            return null;
        }

        for (Cookie cookie: request.getCookies()) {
            if (cookie.getName().equals(cookiename)) {
                return cookie.getValue();
            }
        }
        return null;
    }
}
